#include "Sound.h"

Sound::Sound()
{
	if (SDL_Init(SDL_INIT_AUDIO) != 0) {
		fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}
 
	audio_rate = 22050;
	audio_format = AUDIO_S16SYS;
	audio_channels = 2;
	audio_buffers = 4096;
	 
	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) {
		fprintf(stderr, "Unable to initialize audio: %s\n", Mix_GetError());
		exit(1);
	}
	chunks[SND_EXPLOS] = loadSound("Sounds/explosion.wav");
	chunks[SND_AMB] = loadSound("Sounds/ambience.wav");
	chunks[SND_LASER] = loadSound("Sounds/laser.wav");
	chunks[SND_ZIP] = loadSound("Sounds/zip.wav");
	chunks[SND_SHIELD] = loadSound("Sounds/shield.wav");
	chunks[SND_MISSILE] = loadSound("Sounds/missilelaunch.mp3");
}

Sound::~Sound()
{
	for(int i=0; i<NUM_SOUNDS; i++)
		Mix_FreeChunk(chunks[i]);

	Mix_CloseAudio();
}

Mix_Chunk * Sound::loadSound(char * path){
	
	Mix_Chunk *sound = NULL;
 
	sound = Mix_LoadWAV(path);
	
	if(sound == NULL) {
		fprintf(stderr, "Unable to load WAV file: %s\n", Mix_GetError());
	}
	
	return sound;
	
}

void Sound::playSound(int snd, int loopCount){
	 
	int channel = Mix_PlayChannel(-1, chunks[snd], loopCount);
	if(channel == -1) {
		fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
	}
}

